import 'package:enjoy_plus/models/user_info_model.dart';
import 'package:enjoy_plus/utils/eventbus.dart';
import 'package:enjoy_plus/utils/http.dart';
import 'package:enjoy_plus/utils/logger.dart';
import 'package:enjoy_plus/utils/toast.dart';
import 'package:enjoy_plus/utils/token.dart';
import 'package:enjoy_plus/utils/upload_image.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:dio/dio.dart';

class UserInfo extends StatefulWidget {
  const UserInfo({super.key, required this.userInfo});
  //接收传来的UserInfoModel
  final UserInfoModel userInfo;

  @override
  State<UserInfo> createState() => _UserInfoState();
}

class _UserInfoState extends State<UserInfo> {
  late final TokenManager tokenManager;
  late UserInfoModel userInfo;
  final nickNameController = TextEditingController();
  @override
  void initState() {
    super.initState();
    userInfo = widget.userInfo;
    nickNameController.text = userInfo.nickName ?? '';
  }

  selectAvatar() async {
    String? imageUrl = await UploadImage.selectAvatar(context);
    // logger.d('imageUrl:---$imageUrl---');
    if (imageUrl != '') {
      setState(() {
        userInfo = userInfo.copyWith(avatar: imageUrl);
      });
    }
  }

// 更新昵称
  updateNickName() async {
    if (nickNameController.text.isEmpty) {
      return ToastUtil.showError('昵称不能为空!');
    }
    try {
      var res = await http.put('/userInfo',
          data: {"nickName": nickNameController.text},
          fromJson: (json) => UserInfoModel.fromJson(json));
      if (res.code != 10000) {
        return ToastUtil.showError('修改失败!');
      }
      setState(() {
        userInfo = res.data;
        ToastUtil.showSuccess('修改成功!');
      });
    } catch (e) {
      return ToastUtil.showError('网络异常!');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        centerTitle: true,
        title: const Text('个人信息'),
        leading: IconButton(
          onPressed: () {
            eventBus.fire(BackMine());
            Navigator.pop(context);
          },
          icon: const Icon(Icons.arrow_back_ios),
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            Row(
              children: [
                const Expanded(
                  child: Text('头像'),
                ),
                Material(
                  color: Colors.transparent, // 设置透明背景
                  borderRadius: BorderRadius.circular(12),
                  child: InkWell(
                    onTap: selectAvatar,
                    child: Row(
                      children: [
                        ClipRRect(
                          borderRadius: BorderRadius.circular(100),
                          child: SizedBox(
                            width: 36,
                            height: 36,
                            child: Image.network(
                              userInfo.avatar?.isNotEmpty == true
                                  ? userInfo.avatar!
                                  : 'assets/images/default_avatar.jpg',
                              fit: BoxFit.cover,
                            ),
                          ),
                        ),
                        const SizedBox(width: 8),
                        const Icon(Icons.arrow_forward_ios, size: 16),
                      ],
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 32),
            Row(
              children: [
                const SizedBox(
                  width: 40,
                  height: 20,
                  child: Text('昵称'),
                ),
                Expanded(
                  // flex: 1,
                  child: TextField(
                    controller: nickNameController,
                    textAlign: TextAlign.right, // 文字居右
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: userInfo.nickName?.isEmpty == true
                          ? '请输入昵称'
                          : userInfo.nickName!,
                    ),
                  ),
                ),
                const SizedBox(width: 8),
                const Icon(Icons.edit, size: 16),
              ],
            ),
            const SizedBox(height: 32),
            ElevatedButton(
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xff5690AF),
                foregroundColor: Colors.white,
                fixedSize: const Size(double.infinity, 36),
                minimumSize: const Size(double.infinity, 36),
              ),
              onPressed: updateNickName,
              child: const Text('保存'),
            ),
          ],
        ),
      ),
    );
  }
}
